"""
接口服务模块：股票信息
"""

from app.dto.stockinfo import StockInfoDto
from app.common.constants import StockInfoConstants
from app.common.exception import InvalidParamException
from app.service.stockinfo import StockInfoService


class StockInfoApiService(object):
    """
    股票信息api service类
    """

    @classmethod
    def save(cls, code, name):
        if not code:
            raise InvalidParamException("股票代码不能为空")

        if len(code) != 6:
            raise InvalidParamException("股票代码长度必须为6")

        if not name:
            raise InvalidParamException("股票名称不能为空")

        if len(code) > 32:
            raise InvalidParamException("股票名称长度不能超过32")

        type_enum = StockInfoConstants.Type.get_type(code)
        if not type_enum:
            raise InvalidParamException("股票代码不合法，只支持中国A股")

        # 股票类型
        type_ = type_enum.value[0]
        dto = StockInfoDto(code=code, name=name, type_=type_)

        StockInfoService.save(dto)

        result = dict(code=0, msg="")
        return result

    @classmethod
    def remove_by_id(cls, id_):
        if not isinstance(id_, int):
            raise InvalidParamException("id必须为数字")

        StockInfoService.remove_by_id(id_)
        result = dict(code=0, msg="")
        return result

    @classmethod
    def update(cls, id_, name, status):
        if not isinstance(id_, int):
            raise InvalidParamException("id必须为数字")

        if status:
            if not isinstance(status, int):
                raise InvalidParamException("状态必须为数字")

            status_name = StockInfoConstants.Status.get_value_name(status)
            if not status_name:
                raise InvalidParamException("状态不合法")

        item = StockInfoService.find_by_id(id_=id_)
        if not item:
            raise InvalidParamException("id为{id_}的股票信息不存在".format(id_=id_))

        status = status if status else item['status']
        name = name if name else item['name']
        dto = StockInfoDto(id_=item['id'], code=item['code'], name=name, type_=item['type'], status=status)
        StockInfoService.update(dto)

        result = dict(code=0, msg="")
        return result

    @classmethod
    def find_by_id(cls, _id):
        data = StockInfoService.find_by_id(_id)
        result = dict(code=0, msg="", data=data)
        return result

    @classmethod
    def page_by_param(cls, page=1, page_size=10, **kwargs):
        data = StockInfoService.page_by_param(page, page_size, **kwargs)
        result = dict(code=0, msg="", data=data)
        return result
